// 商品数据
const products = [
    {
        id: 1,
        name: "智能手机",
        price: 1999,
        image: "images/product1.jpg",
        description: "高性能智能手机，6.5英寸屏幕",
        category: "electronics",
        options: {
            color: [
                { value: "黑色", image: "images/product1_black.jpg" },
                { value: "白色", image: "images/product1_white.jpg" },
                { value: "蓝色", image: "images/product1_blue.jpg" }
            ],
            storage: [
                { value: "128GB", image: "images/product1_128gb.jpg" },
                { value: "256GB", image: "images/product1_256gb.jpg" }
            ]
        },
        reviews: [
            { name: "王五", date: "2024-02-01", rating: "★★★★★", content: "这款手机性能超强，拍照也很清晰，非常满意！" },
            { name: "赵六六", date: "2024-02-05", rating: "★★★★", content: "手机运行流畅，外观也好看，值得购买。" }
        ]
    },
    {
        id: 2,
        name: "无线蓝牙耳机",
        price: 299,
        image: "images/product2.jpg",
        description: "高音质无线蓝牙耳机",
        category: "electronics",
        options: {
            color: [
                { value: "黑色", image: "images/product2_black.jpg" },
                { value: "白色", image: "images/product2_white.jpg" }
            ]
        },
        reviews: [
            { name: "孙田", date: "2024-02-10", rating: "★★★★★", content: "耳机音质太棒了，续航也久，爱了！" },
            { name: "周天天", date: "2024-02-15", rating: "★★★★", content: "佩戴很舒适，连接也稳定，不错的选择。" }
        ]
    },
    {
        id: 3,
        name: "男士休闲衬衫",
        price: 159,
        image: "images/product3.jpg",
        description: "纯棉男士休闲衬衫",
        category: "clothing",
        options: {
            size: [
                { value: "S", image: "images/product3_s.jpg" },
                { value: "M", image: "images/product3_m.jpg" },
                { value: "L", image: "images/product3_l.jpg" }
            ],
            color: [
                { value: "蓝色", image: "images/product3_blue.jpg" },
                { value: "黑色", image: "images/product3_black.jpg" }
            ]
        },
        reviews: [
            { name: "吴萌萌", date: "2024-02-20", rating: "★★★★★", content: "衬衫质量很好，纯棉材质很舒服。" },
            { name: "郑和", date: "2024-02-25", rating: "★★★★", content: "款式很时尚，尺码也合适。" }
        ]
    },
    {
        id: 4,
        name: "JavaScript高级程序设计",
        price: 99,
        image: "images/product4.jpg",
        description: "前端开发必备书籍",
        category: "books",
        reviews: [
            { name: "王一一", date: "2023-05-01", rating: "★★★★★", content: "这本书内容很全面，对学习前端很有帮助。" },
            { name: "李木子", date: "2024-03-05", rating: "★★★★", content: "讲解清晰，适合初学者和进阶者。" }
        ]
    },
    {
        id: 5,
        name: "智能电饭煲",
        price: 399,
        image: "images/product5.jpg",
        description: "多功能智能电饭煲",
        category: "home",
        options: {
            capacity: [
                { value: "3L", image: "images/product5_3l.jpg" },
                { value: "5L", image: "images/product5_5l.jpg" }
            ]
        },
        reviews: [
            { name: "张苏苏", date: "2024-03-10", rating: "★★★★★", content: "电饭煲功能很多，煮出来的饭很香。" },
            { name: "刘静淳", date: "2025-05-15", rating: "★★★★", content: "操作简单，外观也好看。" }
        ]
    },
    {
        id: 6,
        name: "进口牛奶",
        price: 69,
        image: "images/product6.jpg",
        description: "新西兰进口纯牛奶",
        category: "food",
        reviews: [
            { name: "陈红", date: "2024-01-20", rating: "★★★★★", content: "牛奶口感醇厚，很新鲜，值得购买。" },
            { name: "杨芳", date: "2024-03-25", rating: "★★★★", content: "味道不错，孩子很喜欢喝。" }
        ]
    },
    {
        id: 7,
        name: "笔记本电脑",
        price: 5999,
        image: "images/product7.jpg",
        description: "高性能轻薄笔记本电脑",
        category: "electronics",
        options: {
            color: [
                { value: "银色", image: "images/product7_silver.jpg" },
                { value: "黑色", image: "images/product7_black.jpg" }
            ],
            storage: [
                { value: "512GB", image: "images/product7_512gb.jpg" },
                { value: "1TB", image: "images/product7_1tb.jpg" }
            ]
        },
        reviews: [
            { name: "黄柳", date: "2024-04-01", rating: "★★★★★", content: "笔记本性能强劲，轻薄便携，非常满意。" },
            { name: "胡景天", date: "2024-04-05", rating: "★★★★", content: "屏幕显示效果好，散热也不错。" }
        ]
    },
    {
        id: 8,
        name: "女士连衣裙",
        price: 199,
        image: "images/product8.jpg",
        description: "夏季新款女士连衣裙",
        category: "clothing",
        options: {
            size: [
                { value: "S", image: "images/product8_s.jpg" },
                { value: "M", image: "images/product8_m.jpg" },
                { value: "L", image: "images/product8_l.jpg" }
            ],
            color: [
                { value: "粉色", image: "images/product8_pink.jpg" },
                { value: "紫色", image: "images/product8_purple.jpg" }
            ]
        },
        reviews: [
            { name: "林娜", date: "2024-04-10", rating: "★★★★★", content: "连衣裙款式很时尚，面料也舒服。" },
            { name: "何妍", date: "2024-04-15", rating: "★★★★", content: "尺码合适，上身效果很好。" }
        ]
    }
];

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 从URL获取商品ID
    const urlParams = new URLSearchParams(window.location.search);
    const productId = parseInt(urlParams.get('id'));

    if (!productId) {
        window.location.href = 'index.html';
        return;
    }

    // 获取商品信息
    const product = products.find(p => p.id === productId);

    if (!product) {
        window.location.href = 'index.html';
        return;
    }

    // 显示商品信息
    document.getElementById('productName').textContent = product.name;
    document.getElementById('productTitle').textContent = product.name;
    document.getElementById('productDescription').textContent = product.description;
    document.getElementById('productPrice').textContent = `¥${product.price.toFixed(2)}`;
    document.getElementById('productImage').src = product.image;

    // 显示商品选项
    const productOptions = document.querySelector('.product-options');
    productOptions.innerHTML = '';
    if (product.options) {
        for (const [optionName, optionValues] of Object.entries(product.options)) {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'option';
            optionDiv.innerHTML = `
                <label>${optionName}:</label>
                <div class="option-values">
                    ${optionValues.map(value => `<button class="option-btn" data-image="${value.image}">${value.value}</button>`).join('')}
                </div>
            `;
            productOptions.appendChild(optionDiv);
        }
    }

    // 选项按钮点击事件
    const optionBtns = document.querySelectorAll('.option-btn');
    optionBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除同一选项组中其他按钮的active类
            const optionGroup = btn.parentNode;
            const groupBtns = optionGroup.querySelectorAll('.option-btn');
            groupBtns.forEach(groupBtn => groupBtn.classList.remove('active'));
            // 添加active类到当前点击的按钮
            btn.classList.add('active');
            // 切换图片
            const image = btn.dataset.image;
            if (image) {
                document.getElementById('productImage').src = image;
            }
        });
    });

    // 数量控制按钮
    const quantityInput = document.querySelector('.quantity-input');
    const minusBtn = document.querySelector('.quantity-btn.minus');
    const plusBtn = document.querySelector('.quantity-btn.plus');

    minusBtn.addEventListener('click', () => {
        let quantity = parseInt(quantityInput.value);
        if (quantity > 1) {
            quantity--;
            quantityInput.value = quantity;
        }
    });

    plusBtn.addEventListener('click', () => {
        let quantity = parseInt(quantityInput.value);
        quantity++;
        quantityInput.value = quantity;
    });

    // 添加购物车事件
    const addToCartBtn = document.getElementById('addToCartBtn');
    if (addToCartBtn) {
        addToCartBtn.addEventListener('click', () => {
            const quantity = parseInt(document.querySelector('.quantity-input').value);
            addToCart(productId, quantity);
        });
    }

    // 显示商品评价
    const reviewList = document.querySelector('.review-list');
    reviewList.innerHTML = '';
    if (product.reviews) {
        product.reviews.forEach(review => {
            const reviewItem = document.createElement('div');
            reviewItem.className = 'review-item';
            reviewItem.innerHTML = `
                <div class="reviewer-info">
                    <span class="reviewer-name">${review.name}</span>
                    <span class="review-date">${review.date}</span>
                    <span class="review-rating">${review.rating}</span>
                </div>
                <div class="review-content">${review.content}</div>
            `;
            reviewList.appendChild(reviewItem);
        });
    }
});

function addToCart(productId, quantity) {
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    const product = products.find(p => p.id === productId);

    if (!product) return;

    const existingItem = cart.find(item => item.id === productId);

    if (existingItem) {
        existingItem.quantity += quantity;
    } else {
        cart.push({
            id: product.id,
            name: product.name,
            price: product.price,
            image: product.image,
            quantity: quantity
        });
    }

    localStorage.setItem('cart', JSON.stringify(cart));
    updateCartCount();
}

function updateCartCount() {
    const cartCountElement = document.getElementById('cartCount');
    if (cartCountElement) {
        const cart = JSON.parse(localStorage.getItem('cart')) || [];
        const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
        cartCountElement.textContent = totalItems;
    }
}